package com.example.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.model.acl.dtos.AclMenuDto;
import com.example.model.acl.pojos.Acl_menu;
import com.example.user.mapper.AclMenuMapper;
import com.example.user.mapper.AclPermissionMapper;
import com.example.user.service.AclMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class AclMenuServiceImpl extends ServiceImpl<AclMenuMapper, Acl_menu> implements AclMenuService {

    @Autowired
    private AclMenuMapper aclMenuMapper;

    private AclMenuDto toDto(Acl_menu aclMenu){
        AclMenuDto aclMenuDto = new AclMenuDto();
        BeanUtils.copyProperties(aclMenu,aclMenuDto);
        return aclMenuDto;
    }

    private void findSubCategory(List<Acl_menu> menuList,List<AclMenuDto> menuDtoList){
        for(AclMenuDto aclMenuDto : menuDtoList){
            List<AclMenuDto> newMenuDtoList = new ArrayList<>();
            for(Acl_menu aclMenu : menuList){
                if(aclMenuDto.getId().equals(aclMenu.getParentId())){
                    newMenuDtoList.add(toDto(aclMenu));
                }
                findSubCategory(menuList,newMenuDtoList);
                newMenuDtoList.sort(Comparator.comparing(AclMenuDto::getSortOrder));
            }
            aclMenuDto.setChildren(newMenuDtoList);
        }
    }

    @Override
    public List<AclMenuDto> getMenuListByUserId(String id) {
        List<Acl_menu> menuList = aclMenuMapper.getMenuListByUserId(id);
        System.out.println(Arrays.toString(menuList.toArray()));
        List<AclMenuDto> menuDtoList = menuList.stream()
                .filter(m -> m.getParentId().equals("0"))
                .map(this::toDto)
                .sorted(Comparator.comparing(AclMenuDto::getSortOrder))
                .collect(Collectors.toList());

        findSubCategory(menuList,menuDtoList);
        return menuDtoList;
    }
}
